package com.alpha.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alpha.bom.Student;
import com.alpha.dao.StudentDao;

/**
 * Servlet implementation class ActivateStudentServlet
 */
@WebServlet("/ActivateStudentServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class ActivateStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(ActivateStudentServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActivateStudentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		logger.info(this.getClass().getSimpleName()+" get method started.");
		Student student = null;
		int student_id;
		
		if(request.getParameter("student_id")!=null){
			student_id = Integer.parseInt(request.getParameter("student_id"));
			StudentDao sDao = new StudentDao();
			try {
				if(sDao.retrieveStudent(student_id)!=null){
					student = sDao.retrieveStudent(student_id);
				}
			} catch (NumberFormatException e) {
				logger.error(e.getMessage());
				response.sendRedirect("StudentsAdminServlet?error=Student+activation+failed.");
				return;
			} catch (NamingException e) {
				logger.error(e.getMessage());
				return;
			} catch (SQLException e) {
				logger.error(e.getMessage());
				return;
			}
			
			if(student!=null){
				if(student.isActivated()){
					student.setActivated(false);
				}else{
					student.setActivated(true);
				}
			
				try {
					sDao.updateStudent(student);
				} catch (NamingException e) {
					logger.error(e.getMessage());
					return;
				} catch (SQLException e) {
					logger.error(e.getMessage());
					return;
				}
				
				if(student.isActivated()){
					response.sendRedirect("StudentsAdminServlet?success=Student+activated!");
				} else {
					response.sendRedirect("StudentsAdminServlet?success=Student+deactivated!");
				}
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		
	}

}
